<!--
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-08-20 21:20:43
 * @LastEditors: 关德参 2257609862@qq.com
 * @LastEditTime: 2024-09-19 17:16:19
 * @FilePath: /task-admin/src/views/teams/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by RSC, All Rights Reserved. 
-->
<template>
  <div class="container">
    <!-- 列表 -->
    <page-content
      ref="contentRef"
      :stripe="true"
      :content-config="contentConfig"
      @add-click="handleOpenDialog"
      @edit-click="handleOpenDialog"
      @resetpwd-click="handleResetpwdClick"
    >
      <template #status="scope">
        <el-switch
          v-model="scope.row.status"
          active-value="normal"
          inactive-value="hidden"
          :loading="scope.row.loading ? true : false"
          :before-change="() => switchBeforeChange(scope.row)"
        />
      </template>
      <template #gender="scope">
        <span>{{
          scope.row.gender == 0 ? $t("common.male") : $t("common.female")
        }}</span>
      </template>
    </page-content>

    <!-- 新增表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="890px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="roleFormRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="32">
          <el-col :span="12">
            <el-form-item :label="$t('common.userName')" prop="username">
              <el-input
                v-model="formData.username"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.nickName')" prop="nickname">
              <el-input
                v-model="formData.nickname"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.ruleType')" prop="rule_type">
              <el-select v-model="formData.rule_type">
                <el-option
                  v-for="item in ruleTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.jobNo')" prop="job_no">
              <el-input
                v-model="formData.job_no"
                :placeholder="$t('common.autofill')"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('common.cellPhoneNumber')" prop="mobile">
              <el-input
                v-model="formData.mobile"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('common.role')" prop="group_id">
              <el-select v-model="formData.group_id">
                <el-option
                  v-for="item in roleOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('common.dateOfBirth')" prop="birthday">
              <el-date-picker
                style="width: 100%"
                v-model="formData.birthday"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :placeholder="$t('common.pleaseSelect')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('common.Gender')" prop="gender">
              <el-select v-model="formData.gender">
                <el-option :key="0" :label="$t('common.male')" :value="0" />
                <el-option :key="1" :label="$t('common.female')" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('common.jobTypes')" prop="type_of_work">
              <el-input
                v-model="formData.type_of_work"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('common.perDiem')" prop="daily_wage">
              <el-input
                type="number"
                v-model="formData.daily_wage"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('common.password')" prop="password">
              <el-input
                v-model="formData.password"
                type="password"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('common.status')" prop="status">
              <el-switch
                v-model="formData.status"
                active-value="normal"
                inactive-value="hidden"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import contentConfig from "./config/content";
import type { IObject } from "@/hooks/usePage";
import { UserForm } from "@/api/user/model";
import type PageContent from "@/components/PageContent/index.vue";
import UserAPI from "@/api/user";
import RoleAPI from "@/api/role";
import { RoleList } from "@/api/role/model";
const { t } = useI18n();
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
const formData = reactive<UserForm>({
  status: "normal",
});
const rules = reactive({
  username: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  nickname: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  mobile: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  rule_type: [
    { required: true, message: t("common.pleaseSelect"), trigger: "blur" },
  ],
  group_id: [
    { required: true, message: t("common.pleaseSelect"), trigger: "blur" },
  ],
  birthday: [
    { required: true, message: t("common.pleaseSelect"), trigger: "blur" },
  ],
  gender: [
    { required: true, message: t("common.pleaseSelect"), trigger: "blur" },
  ],
  type_of_work: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  daily_wage: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  // password: [
  //   { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  // ],
  status: [
    { required: true, message: t("common.pleaseSelect"), trigger: "blur" },
  ],
});

const ruleTypeOption = ref<Options[]>([
  {
    label: t("common.backendManagement"),
    value: "boss",
  },
  {
    label: t("common.manager"),
    value: "manager",
  },
  {
    label: t("common.employee"),
    value: "employee",
  },
]);

// 新增 / 编辑
function handleOpenDialog(row?: IObject) {
  dialog.visible = true;
  if (row?.id) {
    dialog.title = t("common.modifyUser");
    Object.assign(formData, row);
  } else {
    dialog.title = t("common.addUser");
  }
}

/** 关闭弹窗 */
const roleFormRef = ref(ElForm);
function handleCloseDialog() {
  dialog.visible = false;
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  formData.id = undefined;
  formData.status = "normal";
}

/** 提交表单 */
const loading = ref(false);
const contentRef = ref<InstanceType<typeof PageContent>>();
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const Id = formData.id;
      UserAPI.add(formData)
        .then(() => {
          ElMessage.success(
            Id
              ? t("common.modifiedSuccessfully")
              : t("common.newSuccessfullyAdded")
          );
          handleCloseDialog();
          contentRef.value?.fetchPageData({}, true); //重置查询
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}
const handleResetpwdClick = (row: IObject) => {
  ElMessageBox.confirm(t("common.confirmResetPassword"), t("common.warning"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  }).then(function () {
    UserAPI.resetPwd({
      user_id: row.id,
      password: "123456",
    }).then(() => {
      ElMessage.success(t("common.resetPasswordSuccessfully"));
    });
  });
};

const switchBeforeChange = (row: IObject) => {
  row.loading = true;
  return new Promise<boolean>((resolve) => {
    UserAPI.chgStatus({
      user_id: row.id,
      status: row.status === "normal" ? "hidden" : "normal",
    })
      .then(() => {
        ElMessage.success(t("common.updateSuccessfully"));
      })
      .finally(() => {
        row.loading = false;
      });
    return resolve(true);
  });
};

const roleOption = ref<RoleList[]>();
onMounted(() => {
  RoleAPI.getPage({
    page: 1,
    page_size: 999999,
  }).then((data) => {
    roleOption.value = data.list;
  });
});
</script>

<style scoped>
/* @import url(); 引入公共css类 */
</style>
